﻿#include "adclient.h"
#include "ui_adclient.h"
#include <QDebug>
#pragma execution_character_set("utf-8")
QMap<QString,QImage> qMapPicturePath;// 图片路径

//QTcpSocket 的默认缓存区大小是 64KB（65536字节）
AdClient::AdClient(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::AdClient)
{
    ui->setupUi(this);
    this->setWindowIcon(QIcon(":/client.jpg"));
    date = new AdDate(ui->date_lb);//时间
    socket = new AdSocket;// TCP客户端
    weater = new Weather(ui->weather_lb);// 接收天气信息绘制
    rollmsg = new RollMassege(ui->msg_lb, ui->msg_lb);// 滚动信息

    connect(socket, SIGNAL(sig_showWeather(QString,QString,QString)), weater, SLOT(showWeather(QString,QString,QString)));
    connect(socket, SIGNAL(sig_showTxt(QString)), rollmsg, SLOT(showTxt(QString)));
    connect(socket, SIGNAL(sig_showImage(QImage)), this, SLOT(showImage(QImage)));
    connect(socket, SIGNAL(sig_showProgressBar(int,int)), this, SLOT(showProgressBar(int,int)),Qt::QueuedConnection);
    connect(socket, SIGNAL(GUI_WarningSignal(QString,QString,QString,QString)), this, SLOT(GUI_WarningMsg(QString,QString,QString,QString)));

    date->start();//更新时间
    progress = nullptr;
    autoPlayTimer.stop();
    connect(&autoPlayTimer, SIGNAL(timeout()), this, SLOT(autoPlayTimeOut()));

    InitStatusBar();// 初始化底部状态栏
}

AdClient::~AdClient()
{
    delete socket;
    delete ui;
}

// 保存文件
void AdClient::saveFile()
{
    QString fileName=qMapPicturePath.lastKey();
    qDebug()<<"lastKey："<<fileName;
    QImage image=qMapPicturePath.last();
    image.save(fileName);
}

// 初始化底部状态栏
void AdClient::InitStatusBar()
{
    mLocalIP=new QLabel(this);
    mLocalIP->setMinimumWidth(230);
    QString ip = GetLocalIP();
    //    mLocalIP->setText("本地IP:"+ip);
    mLocalIP->setText("本地IP:"+tr("<font color=\"red\">%1</font>").arg(ip));

    serverIP_lb=new QLabel(this);
    serverIP_lb->setMinimumWidth(100);
    serverIP_lb->setText("服务器IP:");
    serverIP=new QLineEdit(this);
    serverIP->setMinimumWidth(200);
    serverIP->setInputMask("000.000.000.000");

    serverPort_lb=new QLabel(this);
    serverPort_lb->setMinimumWidth(60);
    serverPort_lb->setText("Port:");
    serverPort=new QLineEdit(this);
    serverPort->setMinimumWidth(60);
    serverPort->setPlaceholderText("8888");

    connectTcp=new QPushButton("链接",this);
    connectTcp->setMinimumWidth(100);

    ui->statusBar->addWidget(mLocalIP);
    ui->statusBar->addWidget(serverIP_lb);
    ui->statusBar->addWidget(serverIP);
    ui->statusBar->addWidget(serverPort_lb);
    ui->statusBar->addWidget(serverPort);
    ui->statusBar->addWidget(connectTcp);
}


// 获取本地IP
QString AdClient::GetLocalIP()
{
    QList<QHostAddress> list=QNetworkInterface::allAddresses();
    foreach(QHostAddress address,list)
    {
        if(address.protocol()==QAbstractSocket::IPv4Protocol)
        {
            qDebug()<<address.toString();
            return address.toString();
        }
    }
    return "";
}


// 图片显示
void AdClient::showImage(QImage image)
{
    qDebug()<<"显示图片"<<__LINE__;
    QPixmap pixmap=QPixmap::fromImage(image);
    // 内容是否自动缩放，参数true自动缩放
    ui->video_lb->setScaledContents(true);//显示图片的全部
    // 将图片缩放到指定大小，参数ui->label->size()表示缩放的大小，Qt::KeepAspectRatio表示保持图片的宽高比，Qt::SmoothTransformation表示使用平滑缩放算法
    ui->video_lb->setPixmap(pixmap.scaled(ui->video_lb->size(),Qt::KeepAspectRatio,Qt::SmoothTransformation));

    qDebug()<<"图片数量："<<qMapPicturePath.count();
    qDebug()<<"定时器状态："<<autoPlayTimer.isActive();

    if(qMapPicturePath.count()>=2)
    {
        if(!autoPlayTimer.isActive()){
            // 两张以上图片开启播放
            autoPlayTimer.start(5000);
            index=0;
        }
    }
    else
    {
        autoPlayTimer.stop();
    }

    if(qMapPicturePath.count()>=1)
    {
        // 功能没问题，调试注释，避免多次保存
        //saveFile();// 保存文件
    }
}

//进度条显示
void AdClient::showProgressBar(int currentProgress, int finish)
{
    qDebug()<<"进度条显示"<<__LINE__;
    if (!progress)
    {
        //创建进度条
        progress = new QProgressDialog("接收中....", "取消", 0, 100, this);
        progress->setWindowModality(Qt::WindowModal);
        progress->setFixedSize(this->width()*0.3,this->height()*0.3);
        progress->setVisible(true);

    }
    //usleep(500);//在Windows环境下已被弃用
    QThread::msleep(50);//休眠50毫秒
    //更新进度条
    progress->setValue(currentProgress * 100 / finish);

    //如果任务已经完成，隐藏进度条
    if (currentProgress == finish)
    {
        qDebug()<<"进度条显示完成"<<__LINE__;
        progress->hide();
        delete progress;
        progress = nullptr;
    }
}

//自动播放
void AdClient::autoPlayTimeOut()
{
    QList<QString> keyList = qMapPicturePath.keys();//存放的就是QMap的key值

    if(index>=qMapPicturePath.count())// 删除广告时有可能 >
        index=0;

    QImage image=qMapPicturePath.value(keyList.at(index));
    qDebug()<<"自动播放:"<<keyList.at(index);
    showImage(image);

    index++;
}
//设置警报
void AdClient::GUI_WarningMsg(QString title, QString text, QString buttons, QString defaultButton)
{
    Q_UNUSED(buttons)//忽略编译器发出的警告，表明变量event未使用
    Q_UNUSED(defaultButton)
    QMessageBox *box=new QMessageBox(QMessageBox::Warning,title,text,QMessageBox::Cancel,this);
    QTimer::singleShot(5000,this,[=](){
        if(!box->isHidden()&&box->isVisible())
        {
            box->accept();
        }
    });// 5s后必执行
    box->exec();
    return;
}
